<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="发布时间">
        <el-date-picker
          v-model="daterangeCreateTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasRole="['admin','conservator']"
          v-hasPermi="['notice:notice:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasRole="['admin','conservator']"
          v-hasPermi="['notice:notice:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasRole="['admin','conservator']"
          v-hasPermi="['notice:notice:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['notice:notice:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="noticeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column  type="index" label="序号" width="100" align="center" :index="indexMethod" />
      <el-table-column label="公告标题"  prop="title" />
      <el-table-column label="发布人" align="center" prop="createBy" />
      <el-table-column label="发布时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="状态" align="center" prop="status" >
        <template slot-scope="scope">
          <span v-if="scope.row.status == 1">草稿</span>
          <span v-if="scope.row.status == 2">发送</span>
          <span v-if="scope.row.status == 3">撤回</span>
          <span v-if="scope.row.status == 4">删除</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleDetails(scope.row)"
          >详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改通知公告对话框 -->
    <el-dialog :close-on-click-modal='false' :title="title" :visible.sync="open" width="50%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>

        <el-row :gutter="24" type="flex" justify="space-between">
          <el-col :span="11">
            <el-form-item label="公告类型" prop="type">
              <el-select style="width: 100%;" v-model="form.type" placeholder="请选择公告类型">
                <el-option
                  v-for="dict in dict.type.ps_message_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <div style="display: flex;">
              <!-- <el-form-item label="送达范围" >
                <el-switch
                  v-model="isShowSecretary"
                ></el-switch>
              </el-form-item> -->

              <el-form-item label="送达范围" prop="sendUnits">
                <el-radio-group v-model="form.sendUnits">
                  <el-radio label="1">所有</el-radio>
                  <el-radio label="2">指定人员</el-radio>
                </el-radio-group>
              </el-form-item>
            </div>
          </el-col>
        </el-row>

        <el-row v-if="form.sendUnits == 2" :gutter="24" type="flex" justify="space-between">
          <el-col :span="11">
            <el-form-item label="送达单位" prop="unitIds">
              <el-cascader
                  style="width: 100%;"
                  v-model="form.unitIds"
                  placeholder="请选择"
                  class="row_a"
                  :options="deptList"
                   ref='ownArea'

                  :props="{multiple: true, checkStrictly: true ,label:'deptName',value:'deptId'}"
                  :show-all-levels="false"
                  clearable>
              </el-cascader>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="封面图">
          <image-upload :isShowTip='false' v-model="form.coverImage"/>
        </el-form-item>

        <el-form-item label="摘要" prop="abstracts">
          <el-input v-model="form.abstracts" placeholder="请输入摘要" />
        </el-form-item>
        <el-form-item label="内容">
          <editor v-model="form.noticeContent" :height="160"/>
        </el-form-item>

        <el-row :gutter="24" type="flex" justify="space-between">
          <el-col :span="20">
            <div style="display: flex;">
              <el-form-item label="是否跟踪" >
                <el-switch
                  v-model="isAfter"
                ></el-switch>
              </el-form-item>

              <el-form-item label-width="30px" v-if="isAfter">
                <el-radio-group v-model="form.feedbackType">
                  <el-radio label="1">接收情况</el-radio>
                  <el-radio label="2">填写反馈</el-radio>
                </el-radio-group>
              </el-form-item>
            </div>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm(2)">发 布</el-button>
        <el-button type="info" @click="submitForm(1)">暂 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listNotice, getNotice, delNotice, addNotice, updateNotice,noticeRead } from "@/api/notice/notice";
import { listDept } from "@/api/system/dept";
export default {
  name: "Notice",
  dicts: ['ps_message_type'],
  data() {
    return {
      sendTypeList:[
        {
          value:'1',
          label:'接受情况'
        },
        {
          value:'2',
          label:'填写反馈'
        }
      ],
      isShowSecretary:true,
      isAfter:false,
      //单位列表
      deptList:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 通知公告表格数据
      noticeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态；1=草稿；2=发送；3=撤回；4=删除；时间范围
      daterangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        createTime: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
        noticeContent: [
          { required: true, message: "内容不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getUnitList()
  },
  methods: {
    //获取单位列表
    getUnitList(){
      listDept().then(response => {
        let data  =  this.handleTree(response.data, "deptId")[0].children;
        data.map(item=>{
          item.disabled = true
        })
        this.deptList = data
      });
    },
    indexMethod(index) {
       index = (index + 1) + (this.queryParams.pageNum - 1) * this.queryParams.pageSize
       return index
     },
    /** 查询通知公告列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      }
      listNotice(this.queryParams).then(response => {
        this.noticeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        type: null,
        coverImage: null,
        abstracts: null,
        createBy: null,
        createTime: null,
        noticeContent: null,
        sendUnits: "1",
        feedbackType:'0',
        status: 0,
        unitIds:[],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加通知公告";
      this.isAfter = false
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getNotice(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改通知公告";
      });
    },
    //详情
    handleDetails(row){
      noticeRead({noticeId:row.id}).then(res=>{
      })
      this.$router.push({path:'/noticParticulars',query: {id:row.id}})
    },
    /** 提交按钮 */
    submitForm(type) {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.status = type
          if(this.form.hasOwnProperty('unitIds')){
            if(this.form.unitIds && this.form.unitIds.length){
              let deepIds = []
              this.form.unitIds.map(item=>{
                deepIds.push(item[item.length-1])
                this.form.unitIds = deepIds
              })
            }
          }
          if (this.form.id != null) {
            updateNotice(this.form).then( nresponse => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addNotice(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除通知公告编号为"' + ids + '"的数据项？').then(function() {
        return delNotice(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('notice/notice/export', {
        ...this.queryParams
      }, `notice_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style lang="scss" scoped>
  ::v-deep .el-dialog__body{
    max-height:650px;
    overflow-y: auto;
    padding:10px 20px 0 20px !important;
  }
</style>
